<?php

namespace app\common\job;

use ShidianUtil\Api\Tencent\Wechat\Wechat;
use think\facade\Config;
use think\queue\Job;

/**
 * 公众号模板消息
 * Class SubscriptionMessage
 * @package app\common\job
 */
class SubscriptionMessage
{
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $touser = $data['touser'] ?? '';
        $template_id = $data['template_id'] ?? '';
        $template_data = $data['data'] ?? [];
        $pagepath = $data['pagepath'] ?? '';
        $url = $data['url'] ?? '';

        $appid = Config::get('wechat.' . MINIPROGRAM . '.AppID');

        if (not_blank($url) && is_blank($pagepath)) {
            $miniprogram = [];
        } else {
            $miniprogram = [
                'appid' => $appid,
                'pagepath' => $pagepath
            ];
        }

        $this->getWechat()->subscription(SUBSCRIPTION)
            ->templateMessage()
            ->send($touser, $template_id, $url, $miniprogram, $template_data);

        $job->delete();
    }

    private function getWechat(): Wechat
    {
        return app(Wechat::class);
    }
}
